<template>
  <ReModal
    class="create-box"
    width="92%"
    :visible="visible"
    :title="title"
    :beforeClose="modalOnHide"
    :onHide="modalOnHide"
    :onOk="modalOnOk"
    :isLoading="loading"
  >
    <template v-slot:childDom>
      <div>
        <el-form
          class="create-form-box"
          ref="createForm"
          :rules="rules"
          :model="createFormData"
          label-width="120px"
        >
          <el-form-item label="设备名称" prop="name">
            <el-input
              size="small"
              v-model="createFormData.name"
              maxlength="50"
              placeholder="请输入设备名称"
            />
          </el-form-item>

          <el-form-item label="型号名称" prop="modelCode">
            <el-input
              size="small"
              v-model="createFormData.modelCode"
              maxlength="50"
              placeholder="请输入型号名称"
            />
          </el-form-item>

          <el-form-item label="品牌名称" prop="brandName">
            <el-input
              size="small"
              v-model="createFormData.brandName"
              maxlength="50"
              placeholder="请输入品牌名称"
            />
          </el-form-item>
          <el-form-item label="类型" prop="typeCodes">
            <el-select
              v-model="createFormData.typeCodes"
              filterable
              clearable
              placeholder="请选择类型"
              class="mr-10"
              size="small"
              multiple
            >
              <el-option
                :label="role.label"
                :value="role.value"
                v-for="role in types"
                :key="role.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input
              size="small"
              v-model="createFormData.price"
              placeholder="请输入价格"
              maxlength="50"
            />
          </el-form-item>

          <el-form-item label="所属地区" prop="addressIds">
            <el-select
              v-model="createFormData.addressIds"
              filterable
              :filter-method="filterMethod"
              clearable
              placeholder="请选择所属地区"
              class="mr-10"
              multiple
              size="small"
              :reserve-keyword="true"
              :collapse-tags="true"
            >
              <el-option
                v-for="item in addressList"
                :value="item.id"
                :key="item.id"
                :label="item.addressName"
              >
                {{ item.addressName }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属经销商" prop="counsellorName">
            <el-input
              size="small"
              v-model="createFormData.counsellorName"
              placeholder="请输入所属经销商"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="经销商联系方式" prop="counsellorPhone">
            <el-input
              size="small"
              v-model="createFormData.counsellorPhone"
              placeholder="请输入经销商联系方式"
              maxlength="50"
            />
          </el-form-item>
          <el-form-item label="上市时间" prop="produceTime">
            <el-date-picker
              v-model="createFormData.produceTime"
              placeholder="选择日期"
              size="small"
              value-format="yyyy"
              type="year"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item class="item-100" label="主图" prop="masterItemVOList">
            <UploadImgs
              @uploadOnChange="mainsUploadOnChange"
              :renderList="createFormData.masterItemVOList"
              :limit="1"
            />
          </el-form-item>
          <el-form-item class="item-100" label="轮播图" prop="imageItemVOList">
            <UploadImgs
              @uploadOnChange="rangUploadOnChange"
              :renderList="createFormData.imageItemVOList"
              :limit="5"
            />
          </el-form-item>
          <el-form-item
            class="item-100"
            label="应用范围"
            prop="scopeItemVOList"
          >
            <el-radio-group v-model="introduceType" style="margin-right: 20px">
              <el-radio :label="3">文字段</el-radio>
              <el-radio :label="6">图片</el-radio>
              <el-radio :label="9">应用列表</el-radio>
            </el-radio-group>
            <el-button
              style="width: 80px !important"
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="introduceAddItem"
              v-if="introduceType == 9"
            >
              新增
            </el-button>
            <!-- 文字段类型 -->
            <div v-if="introduceType == '3'">
              <el-input
                size="small"
                type="textarea"
                v-model="text"
                placeholder="请输入文字段"
                maxlength="256"
                :rows="2"
                style="width: 450px"
              />
            </div>
            <div v-if="introduceType == '6'" class="pic-text-box">
              <UploadImgs
                :isShow="false"
                :renderList="pic_text"
                @uploadOnChange="pic_textUploadOnChange"
              />
              <div
                v-for="(item, index) in pic_text"
                :key="item.picUrl"
                class="image-item"
              >
                <div class="pic-text-image-preview">
                  <!-- <img :src="item.picUrl" class="image" /> -->
                  <el-image
                    :lazy="true"
                    :src="item.picUrl"
                    :preview-src-list="[item.picUrl]"
                  >
                    <div slot="placeholder" class="image-slot">
                      加载中<span class="dot">...</span>
                    </div>
                  </el-image>
                </div>
                <el-input
                  v-if="item.picUrl"
                  v-model="item.description"
                  placeholder="请输入图片描述"
                  class="image-description"
                />
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  class="remove-btn"
                  size="mini"
                  @click="removePicText(index)"
                />
              </div>
            </div>
            <div v-if="introduceType == '9'">
              <InputFrame
                ref="InputFrame"
                :isAdd="false"
                v-model="text_text"
                mode="double"
                button-text="添加"
                placeholder1="请输入"
                placeholder2="请输入"
              />
            </div>
          </el-form-item>
          <el-form-item
            class="item-100"
            label="设备特点"
            prop="introduceItemVOList"
          >
            <InputFrame
              v-model="introduceItemVOList"
              mode="single"
              buttonText="添加"
            />
          </el-form-item>
          <el-form-item
            class="item-100"
            label="技术参数"
            prop="paramItemVOList"
          >
            <InputFrame
              v-model="paramItemVOList"
              mode="double"
              button-text="添加"
              placeholder1="请输入"
              placeholder2="请输入"
            />
          </el-form-item>
        </el-form>
      </div>
    </template>
  </ReModal>
</template>

<script>
import ReModal from "@/components/ReModal/index.vue";
import UploadImgs from "./UploadImgs.vue";
import { types } from "@/constant.js";
import { addEquipmentItem, editEquipmentItem } from "@/api/equipment.js";
import InputFrame from "./components/InputFrame/index.vue";
import { getAddressList } from "@/api/address-info-manage.js";

export default {
  components: {
    ReModal,
    UploadImgs,
    InputFrame,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    type: {
      tyep: String,
      default: "add",
    },
    item: {
      tyep: Object,
      default: {},
    },
  },
  computed: {
    title() {
      return `${this.type === "add" ? "新增" : "编辑"}设备`;
    },
  },

  data() {
    return {
      addressList: [],
      text: "", //文字段
      pic_text: [], //文字+图片
      text_text: [], //文字+文字
      introduceItemVOList: [], //设备特点
      paramItemVOList: [], //技术参数图
      loading: false,
      types,
      introduceType: 3,
      createFormData: {
        typeCodes: [],
        counsellorName: "庄经理",
        counsellorPhone: "13342757779",
        masterItemVOList: [],
        imageItemVOList: [],
        paramItemVOList: [],
        scopeItemVOList: [],
        introduceItemVOList: [],
        addressIds: [],
      },
      rules: {
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        brandName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
        ],
        modelCode: [
          { required: true, message: "请输入型号名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        addressIds: [
          { required: true, message: "请选择所属地区", trigger: "blur" },
        ],
        // counsellorName: [
        //   { required: true, message: "请输入所属经销商", trigger: "blur" },
        // ],
        // counsellorPhone: [
        //   { required: true, message: "请输入经销商联系方式", trigger: "blur" },
        // ],
        typeCodes: [{ required: true, message: "请选择类型", trigger: "blur" }],
      },
    };
  },
  created() {
    const { id } = this.item;
    if (id) {
      const { imageItemVOList = [], masterItemVOList = [], remark } = this.item;
      const parseRemark = remark ? JSON.parse(remark) : {};
      if (Object.keys(parseRemark).length > 0) {
        this.introduceItemVOList = parseRemark.introduceItemVOList;
        this.paramItemVOList = parseRemark.paramItemVOList;
        this.text = parseRemark.scopeItemVOList.text;
        this.pic_text = parseRemark.scopeItemVOList.picText;
        this.text_text = parseRemark.scopeItemVOList.textText;
        let type = 3;
        const { scopeItemVOList } = parseRemark;
        console.log("scopeItemVOList", scopeItemVOList);
        if (
          Array.isArray(scopeItemVOList.picText) &&
          scopeItemVOList.picText.length
        ) {
          type = 6;
        } else if (
          Array.isArray(scopeItemVOList.textText) &&
          scopeItemVOList.textText.length
        ) {
          type = 9;
        }
        this.introduceType = type;
      }
      this.createFormData = {
        ...this.item,
        imageItemVOList: imageItemVOList.map((item) => {
          return {
            ...item,
            picUrl: item.url,
            status: "success",
          };
        }),
        masterItemVOList: masterItemVOList.map((item) => {
          return {
            ...item,
            picUrl: item.url,
            status: "success",
          };
        }),
      };
    }
    this.getAddressListFunc();
  },
  methods: {
    filterMethod(e) {
      if (e) {
        this.addressList = this.allAddressList.filter(
          (item) =>
            item.provinceName.includes(e) ||
            item.cityName.includes(e) ||
            item.countyName.includes(e)
        );
      } else {
        this.addressList = this.allAddressList;
      }
    },
    getAddressListFunc() {
      getAddressList({
        pageSize: 300,
        page: 1,
      }).then((res) => {
        const { data } = res;
        const { records } = data;
        this.addressList = records;
        this.allAddressList = JSON.parse(JSON.stringify(records));
      });
    },
    mainsUploadOnChange(data) {
      this.createFormData.masterItemVOList = data.map((item) => {
        if (item.status === "success") {
          return item;
        }
        return {};
      });
    },
    rangUploadOnChange(data) {
      console.log(data);
      this.createFormData.imageItemVOList = data.map((item) => {
        if (item.status === "success") {
          return item;
        }
        return {};
      });
      console.log("this.imageItemVOList", this.createFormData.imageItemVOList);
    },
    pic_textUploadOnChange(data) {
      console.log(data);
      this.pic_text = data.map((item) => {
        // 如果是新上传的文件，初始化描述字段
        console.log(item);
        if (item.status === "success") {
          if (!item.hasOwnProperty("description")) {
            return {
              ...item,
              description: "",
            };
          }
          return item;
        }
        return {};
      });
      console.log("this.pic_text", this.pic_text);
    },
    modalOnOk() {
      console.log(this.createFormData);
      this.$refs.createForm.validate(async (valid) => {
        if (valid) {
          const remark = JSON.stringify({
            introduceItemVOList: this.introduceItemVOList,
            paramItemVOList: this.paramItemVOList,
            scopeItemVOList: {
              text: this.introduceType === 3 ? this.text : "",
              picText: this.introduceType === 6 ? this.pic_text : [],
              textText: this.introduceType === 9 ? this.text_text : [],
            },
          });
          const {
            name,
            modelCode,
            brandName,
            typeName,
            price,
            produceTime,
            counsellorName,
            counsellorPhone,
            masterItemVOList,
            imageItemVOList,
            addressIds,
            typeCodes = [],
          } = this.createFormData;
          const par = {
            ...this.createFormData,
            typeNames: typeCodes.map(
              (code) => types.find((el) => el.value === code)?.label || ""
            ),
            masterItemVOList: masterItemVOList.map((item) => {
              return {
                name: item.name,
                url: item.picUrl,
              };
            }),
            imageItemVOList: imageItemVOList.map((item) => {
              return {
                name: item.name,
                url: item.picUrl,
              };
            }),
            paramItemVOList: [],
            scopeItemVOList: [],
            introduceItemVOList: [],
            introductionInfoList: [],
            paramInfoVO: {},
            remark,
          };
          /**
            text: "", //文字段
            pic_text: [{}], //文字+图片
            text_text: [], //文字+文字
            introduceItemVOList: [], //设备特点
            paramItemVOList: [], //技术参数图
          */
          this.loading = true;
          const api = this?.item?.id ? editEquipmentItem : addEquipmentItem;
          api(par)
            .then(() => {
              this.$emit("onOk");
              this.$message.success(this?.item?.id ? "编辑成功" : "新增成功");
            })
            .finally(() => {
              setTimeout(() => {
                this.loading = false;
              }, 200);
            });
        }
      });
    },
    modalOnHide() {
      this.$emit("onHide");
    },
    introduceAddItem() {
      switch (this.introduceType) {
        case 3:
          break;
        case 6:
          break;
        case 9:
          this.$refs.InputFrame.addInput();
          break;
        default:
          break;
      }
    },
    removePicText(index) {
      this.pic_text = this.pic_text.filter((_, i) => i !== index);
    },
  },
};
</script>
<style scoped lang="scss">
.create-box {
  ::v-deep.create-form-box {
    display: flex;
    flex-wrap: wrap;
    > div {
      flex: 0 0 25%;
      .el-input,
      .el-select {
        width: 100%;
      }
    }
    .item-100 {
      flex: 0 0 100%;
    }
    .yyfw-item {
      .el-form-item__content {
        > div {
          display: flex;
          margin-bottom: 10px;
          .label {
            min-width: 120px;
          }
        }
      }
    }
    .pic-text-box {
      display: flex;
      width: 100%;
      flex-wrap: wrap;
      .upload-imgs {
        flex: 0 0 100%;
        margin-bottom: 10px;
      }
      .image-item {
        flex: 0 0 25%;
        margin-right: 20px;
        margin-bottom: 10px;
        position: relative;
        .remove-btn {
          position: absolute;
          right: 0;
          top: 0;
        }
      }
    }
    .pic-text-image-preview {
      .el-image {
        width: 60px;
        height: 60px;
        line-height: 60px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
      }
    }
  }
}
</style>
